package com.krm;

//import com.sun.tools.javac.util.StringUtils;

import java.util.List;

public class ToMySql extends ToSql{


    /**
     * 转成 sql create table
     * @param exceBeanList
     * @return
     */
    @Override
    public String toSql(List<ExcelBean> exceBeanList){
        StringBuilder sb = new StringBuilder();

        if(exceBeanList==null||exceBeanList.size()<=0){
            return "Excel有问题未能解析出数据";
        }
        for(ExcelBean eb : exceBeanList){
            String pkid = "";
            if(eb ==null){
                continue;
            }
            sb.append("\r\n");
            sb.append("\r\n");


            sb.append(" DROP TABLE "+eb.getTableName() +";\r\n");
            sb.append(" CREATE TABLE "+eb.getTableName() +"(\n");
            List<TableBean> listTableBean =  eb.getTableBean();
            int conut = 0;

            for(TableBean tb : listTableBean) {
                if (tb == null) {
                    continue;
                }

                String clunmeName = tb.getClunmeName().trim();
                if("".equals(clunmeName)||clunmeName==null){
                    continue;
                }

                sb.append("  "+clunmeName);
                if(clunmeName.length()!=20){
                    for(int i=0;i<(25-clunmeName.length());i++)
                    sb.append(" ");
                }

                if(tb.getType().contains("(")||"INTEGER".equalsIgnoreCase(tb.getType().trim())){
                    sb.append("  " + tb.getType().trim());
                }else {
                    sb.append("  " + tb.getType().trim() + "(" + Integer.parseInt(tb.getLength().trim()) + "");

                    if (!"".equals(tb.getRecision() ) && tb.getRecision() != null) {
                        sb.append("," + Integer.parseInt(tb.getRecision().trim()));
                    }
                    sb.append(") ");
                }
                if ( !"".equals(tb.getIsPkid())&&tb.getIsPkid()!=null ){
                    sb.append("  not null ");
                }

                if(!"".equals(tb.getIsPkid())&&tb.getIsPkid()!=null){
                    pkid+= tb.getClunmeName().trim()+",";
                }

                String tbCommt = tb.getCommt().trim();
                if(!"".equals(tbCommt)&&tbCommt!=null) {
                    String  comment = "  COMMENT '" +tbCommt + "'" ;
                    sb.append(comment);
                }
                sb.append(",\r\n");
                conut++;
            }

            if(pkid!=""&&pkid!=null){
                pkid = pkid.substring(0,pkid.length()-1);
                sb.append("PRIMARY KEY ("+pkid+")\r\n");
            }
            sb.append(") ENGINE=INNODB AUTO_INCREMENT=200 COMMENT = '"+eb.getTableCommt()+"';\r\n");
        }

        sb.append("commit;");

        return sb.toString();
    }
}
